import { config } from '@vue/test-utils';

// Mock uni-app API
global.uni = {
  // 页面导航
  navigateTo: jest.fn(),
  redirectTo: jest.fn(),
  reLaunch: jest.fn(),
  switchTab: jest.fn(),
  navigateBack: jest.fn(),

  // 数据存储
  setStorageSync: jest.fn(),
  getStorageSync: jest.fn(() => null),
  removeStorageSync: jest.fn(),
  clearStorageSync: jest.fn(),

  // 网络请求
  request: jest.fn(() => Promise.resolve({
    statusCode: 200,
    data: { success: true, data: {} }
  })),

  // 界面交互
  showToast: jest.fn(),
  showModal: jest.fn(() => Promise.resolve({ confirm: true })),
  showLoading: jest.fn(),
  hideLoading: jest.fn(),
  showActionSheet: jest.fn(),

  // 下拉刷新
  stopPullDownRefresh: jest.fn(),

  // 系统信息
  getSystemInfoSync: jest.fn(() => ({
    platform: 'h5',
    statusBarHeight: 20
  })),

  // 扫码
  scanCode: jest.fn(() => Promise.resolve({
    result: 'test-qr-code'
  }))
};

// Mock wx API (微信小程序)
global.wx = global.uni;

// Mock getCurrentPages
global.getCurrentPages = jest.fn(() => []);

// Mock getApp
global.getApp = jest.fn(() => ({
  globalData: {}
}));

// 配置Vue Test Utils
config.mocks = {
  $store: {
    state: {
      auth: {
        isAuthenticated: false,
        userInfo: null,
        token: ''
      }
    },
    getters: {
      'auth/isLoggedIn': false,
      'auth/points': 0
    },
    commit: jest.fn(),
    dispatch: jest.fn()
  }
};

// 全局测试工具
global.testUtils = {
  // 创建模拟用户数据
  createMockUser: (overrides = {}) => ({
    id: 1,
    nickname: '测试用户',
    phone: '13800138000',
    role: 'user',
    points: 100,
    ...overrides
  }),

  // 创建模拟订单数据
  createMockOrder: (overrides = {}) => ({
    id: 1,
    orderNumber: 'TEST123456',
    status: 'pending',
    totalPoints: 50,
    User: {
      nickname: '测试用户',
      phone: '13800138000'
    },
    OrderItems: [{
      Product: {
        name: '测试商品',
        specification: '规格1'
      },
      quantity: 1,
      pointsUsed: 50
    }],
    createdAt: new Date(),
    ...overrides
  }),

  // 创建模拟积分记录
  createMockPointsRecord: (overrides = {}) => ({
    id: 1,
    type: 'earn',
    amount: 10,
    source: 'ad_watch',
    description: '观看广告奖励',
    created_at: new Date(),
    ...overrides
  }),

  // 模拟API响应
  mockApiResponse: (data, success = true) => ({
    statusCode: success ? 200 : 400,
    data: {
      success,
      data: success ? data : undefined,
      message: success ? undefined : '请求失败'
    }
  }),

  // 等待Vue更新
  async nextTick() {
    await new Promise(resolve => setTimeout(resolve, 0));
  },

  // 模拟用户登录状态
  mockUserLogin: (user = null) => {
    const mockUser = user || testUtils.createMockUser();
    
    global.uni.getStorageSync.mockImplementation((key) => {
      if (key === 'token') return 'mock-token';
      if (key === 'userInfo') return mockUser;
      return null;
    });

    config.mocks.$store.state.auth = {
      isAuthenticated: true,
      userInfo: mockUser,
      token: 'mock-token'
    };

    config.mocks.$store.getters = {
      'auth/isLoggedIn': true,
      'auth/points': mockUser.points
    };
  },

  // 清除登录状态
  clearUserLogin: () => {
    global.uni.getStorageSync.mockReturnValue(null);
    
    config.mocks.$store.state.auth = {
      isAuthenticated: false,
      userInfo: null,
      token: ''
    };

    config.mocks.$store.getters = {
      'auth/isLoggedIn': false,
      'auth/points': 0
    };
  }
};

// 每个测试前重置mocks
beforeEach(() => {
  jest.clearAllMocks();
  testUtils.clearUserLogin();
});

// 设置测试超时
jest.setTimeout(30000);